#include <d3d9.h>
#include <d3dx9.h>
#include <time.h>
#include <stdio.h>
#include "Information.h"
#include "Game2DManager.h"

HWND hwnd;
HINSTANCE hInst;
GameManager * _game;

bool initWindows(HINSTANCE hInst);
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd )
{
	if(!initWindows(hInstance))
		return false;

	_game = new GameManager();

	if(!_game->Init(hInstance, hwnd))
	{
		MessageBox(hwnd,"Loi khoi tao Game", "Error", MB_OK);
		return false;
	}
	MSG msg;
	ZeroMemory(&msg,sizeof(msg));
	bool done = true ;
	DWORD frame_start = GetTickCount();
	DWORD tick_per_frame = 1000 / FRAME_RATE;

	while (done)
	{
		if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
		{
			if(msg.message==WM_QUIT)
				done = false;
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		else
		{
			//Game loop
			DWORD now = GetTickCount();


			if (now - frame_start >= tick_per_frame) 
			{
				_game->Run(hwnd,tick_per_frame);
				frame_start = now;
			}
			else
				Sleep(1);
		}
	}
	return (int)msg.wParam;

}
bool initWindows(HINSTANCE hInst)
{
	WNDCLASSEX wc;
	wc.cbClsExtra  = 0;
	wc.cbSize = sizeof(WNDCLASSEX);
	wc.cbWndExtra = 0;
	wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hIcon = 0;
	wc.hIconSm = 0;
	wc.hInstance = hInst;
	wc.lpfnWndProc = (WNDPROC)(WndProc);
	wc.lpszClassName = APP_CLASS;
	wc.lpszMenuName = NULL;
	wc.style = CS_HREDRAW | CS_VREDRAW;
	RegisterClassEx(&wc);
	hwnd = CreateWindow (APP_CLASS, "",
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		WINDOW_WIDTH,
		WINDOW_HEIGHT,
		NULL,
		NULL,hInst,NULL);
	if(!hInst)
		return false;
	ShowWindow(hwnd,SW_SHOW);
	UpdateWindow(hwnd);
	return true;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch(message)
	{
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	}
	return DefWindowProc(hwnd,message,wParam,lParam);
}